/**
 * @license
 * Copyright 2025 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { AIError } from '../errors';
import { AI, AIErrorCode } from '../public-types';
import { AIService } from '../service';
import { ApiSettings } from '../types/internal';

/**
 * Initializes an {@link ApiSettings} object from an {@link AI} instance.
 *
 * @internal
 */
export function initApiSettings(ai: AI): ApiSettings {
  if (!ai.app?.options?.apiKey) {
    throw new AIError(
      AIErrorCode.NO_API_KEY,
      `The "apiKey" field is empty in the local Firebase config. Firebase AI requires this field to contain a valid API key.`,
    );
  } else if (!ai.app?.options?.projectId) {
    throw new AIError(
      AIErrorCode.NO_PROJECT_ID,
      `The "projectId" field is empty in the local Firebase config. Firebase AI requires this field to contain a valid project ID.`,
    );
  } else if (!ai.app?.options?.appId) {
    throw new AIError(
      AIErrorCode.NO_APP_ID,
      `The "appId" field is empty in the local Firebase config. Firebase AI requires this field to contain a valid app ID.`,
    );
  }

  const apiSettings: ApiSettings = {
    apiKey: ai.app.options.apiKey,
    project: ai.app.options.projectId,
    appId: ai.app.options.appId,
    automaticDataCollectionEnabled: ai.app.automaticDataCollectionEnabled,
    location: ai.location,
    backend: ai.backend,
  };

  if ((ai as AIService).appCheck) {
    if (ai.options?.useLimitedUseAppCheckTokens) {
      apiSettings.getAppCheckToken = () => (ai as AIService).appCheck!.getLimitedUseToken();
    } else {
      apiSettings.getAppCheckToken = () => (ai as AIService).appCheck!.getToken();
    }
  }

  if ((ai as AIService).auth?.currentUser) {
    apiSettings.getAuthToken = () => (ai as AIService).auth!.currentUser!.getIdToken();
  }

  return apiSettings;
}
